#include "netaddress.h"

#include <cstring>

#ifdef __linux__
#   include <arpa/inet.h>
#else
#   include <WinSock2.h>
#endif

namespace tool{ namespace net{

uint32_t TransAddr(const char* addr)
{ return FromNetOrderL(::inet_addr(addr)); }

std::string TransAddr(uint32_t addr)
{
    char buffer[18];
    auto bytes = reinterpret_cast<const uint8_t*>(&addr);
    std::snprintf(buffer,sizeof(buffer),"%d.%d.%d.%d",bytes[3], bytes[2], bytes[1], bytes[0]);
    return buffer;
}


NetAddress::NetAddress(const sockaddr *sock)
{
    auto* p = reinterpret_cast<const sockaddr_in*>(sock);
    m_ip = FromNetOrderL(p->sin_addr.s_addr);
    m_port = FromNetOrderS(p->sin_port);
}

NetAddress::NetAddress(const sockaddr_in *sock)
{
    m_ip = FromNetOrderL(sock->sin_addr.s_addr);
    m_port = FromNetOrderS(sock->sin_port);
}

NetAddress::NetAddress(const std::string& str)
    :m_ip(0),m_port(0)
{
    auto pos = str.find_first_of(':');
    if(pos == std::string::npos){
        return;
    }
    if(str.find_last_of(':')!=pos){
        return;
    }

    std::string strIp = str.substr(0,pos);
    std::string strPort = str.substr(pos+1);
    m_ip = tool::net::TransAddr(strIp.data());
    m_port = std::stoi(strPort);
}

std::string NetAddress::toString() const
{
    char data[32] = {};
    const auto* ptr = reinterpret_cast<const uint8_t*>(&m_ip);
    sprintf(data,"%d.%d.%d.%d:%d",ptr[3],ptr[2],ptr[1],ptr[0],m_port);
    return std::string(data);
}


}}//namespace tool::net
